
//
//  ParkingController.m
//  PropertyMananger
//
//  Created by bh on 17/1/12.
//  Copyright © 2017年 BH. All rights reserved.
//

#import "ParkingController.h"
#import "ParkingCell.h"
#import "CarNumController.h"
#import "ParkingNumController.h"
#import "PullDownMenu.h"
#import "MCSearchBar.h"
#import "ParkingQueryCell.h"
#import "ParkingQueryModel.h"
#import "CarNumQueryModel.h"

@interface ParkingController ()<PullDownMenuDelegate,UISearchBarDelegate,UITextFieldDelegate,UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout,UIAlertViewDelegate>

/*layout*/
@property (nonatomic,strong)  UICollectionViewFlowLayout * layout;
/**数据源**/
@property (nonatomic,strong) NSArray * queryTitleArray;
@property (nonatomic,strong) NSMutableArray * infoArray;


@property (nonatomic,strong) PullDownMenu * menu;

@property (nonatomic,retain) NSMutableArray *arr;
@property (nonatomic,strong) UICollectionView * collectionView;

//车位号数据源
@property (nonatomic,strong) NSMutableArray * parkingNumArray;
@property (nonatomic,strong) NSMutableArray * carNumArray;

@end

@implementation ParkingController

static NSString * cellID = @"parkingCellID";
static  NSString * headerViewID = @"headerViewID";

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    [self initTitleViewName:@"请选择查询方式"];
    [self setupCollectionView];
    
    [self setupUI];
    [self setupSearchBar];
    //  [self getParkingData];
   [self createPlaceHolder];
    
}
#pragma mark - 下拉列表
- (void)setupUI
{
    
    self.queryTitleArray = @[@[@"车牌号", @"车位号"]];
    self.menu = [[PullDownMenu alloc] init];
    self.menu.array = self.queryTitleArray;
    self.menu.delegate = self;
    
    self.menu.frame = CGRectMake(0, 0, self.menu.frame.size.width, self.menu.frame.size.height);
    self.menu.backgroundColor = [UIColor whiteColor];
    
    [self.view addSubview:self.menu];
    
}
#pragma mark - 搜索框
- (void)setupSearchBar
{
    self.searchBar = [[MCSearchBar alloc] initWithFrame:CGRectMake(80, 7.5, self.view.bounds.size.width - 90, 35) placeholder:nil];
    self.searchBar.delegate = self;
    self.searchBar.placeholder = @"请输入查询信息";
    self.searchBar.barTintColor = BHColor(237, 237, 237);
    [self.menu addSubview:self.searchBar];
    [self.searchBar setBackgroundColor:BHColor(237, 237, 237)];
    self.searchBar.layer.cornerRadius = 18.0f;
    self.searchBar.layer.masksToBounds = YES;
    self.searchBar.layer.borderWidth = 0.5;
    self.searchBar.layer.borderColor = BHColor(237, 237, 237).CGColor;
    self.searchBar.backgroundColor = BHColor(237, 237, 237);
    self.searchText = @"";
    
    self.searchBar.searchBarStyle = UISearchBarStyleDefault;
    DLog(@"%ld",self.queryType);
    
    self.resultArr = [[NSMutableArray alloc]init];
    self.parkingNumArray = [[NSMutableArray alloc]init];
    self.carNumArray = [[NSMutableArray alloc]init];
    
}
#pragma mark - collectionView
- (void)setupCollectionView
{
    self.layout = [[UICollectionViewFlowLayout alloc] init];
    
    self.collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 50, BHscreenW, BHscreenH - 50 - 64) collectionViewLayout:self.layout];
    [self.view addSubview:self.collectionView];
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    
    self.collectionView.pagingEnabled = YES;
    self.collectionView.bounces = NO;
    
    self.collectionView.showsHorizontalScrollIndicator = NO;
    self.collectionView.showsVerticalScrollIndicator = NO;
    self.collectionView.backgroundColor = [UIColor whiteColor];
    
    [self.collectionView registerClass:[ParkingQueryCell class] forCellWithReuseIdentifier:cellID];
    [self.collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:headerViewID];
    
}

// 实现代理,选择查询方式
#pragma mark - PullDownMenuDelegate
- (void)PullDownMenu:(PullDownMenu *)pullDownMenu didSelectRowAtColumn:(NSInteger)column row:(NSInteger)row
{
    NSLog(@"%ld -- %ld", column, row);
    self.queryType = row;
    
//    //请选择查询方式
//    [self initTitleViewName:@"请选择查询方式"];
//    self.searchBar.placeholder = @"请输入查询信息";
//    [self.parkingNumArray removeAllObjects];
//    [self.carNumArray removeAllObjects];
//    [self.resultArr removeAllObjects];
//    [self.collectionView reloadData];
//    self.placehoderImg.hidden = NO;
//    self.titleLabel.hidden = NO;
    
    if (row == 0)
    {

        //车牌号查询
        [self initTitleViewName:@"车牌号查询"];
        self.searchBar.placeholder = @"请输入后四位车牌号";
        
        [self.carNumArray removeAllObjects];
        [self.resultArr removeAllObjects];
        [self.collectionView reloadData];
        
        self.placehoderImg.hidden = NO;
        self.titleLabel.hidden = NO;
        
    }else if (row == 1)
    {
        //车辆查询
        [self initTitleViewName:@"车位编号查询"];
        self.searchBar.placeholder = @"请输入车位编号";
        [self.parkingNumArray removeAllObjects];
        [self.resultArr removeAllObjects];
        [self.collectionView reloadData];
        
        self.placehoderImg.hidden = NO;
        self.titleLabel.hidden = NO;
    }
    
    
}
#pragma mark - 代理方法
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    if (self.isSearch) {
        return self.resultArr.count ;
    }else{
        if (self.queryType == 0) {
            
       // return self.isSearch ? self.parkingNumArray.count: 0;
          return self.carNumArray.count;
            
        }else if (self.queryType == 1){
            
          // return  self.isSearch ? self.carNumArray.count: 0;
           
             return self.parkingNumArray.count;
        }
        
    }
    return 0;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    ParkingQueryCell * parkingCell = [collectionView dequeueReusableCellWithReuseIdentifier:cellID forIndexPath:indexPath];
    
    if (self.isSearch) {
        parkingCell.numLabel.text = self.resultArr[indexPath.row];
    }else{
        if (self.queryType == 0) {
            
            CarNumQueryModel * model = self.carNumArray[indexPath.row];
            parkingCell.numLabel.text = model.CarNo;
            
            
        }else if (self.queryType == 1){
            
           
            ParkingQueryModel * model = self.parkingNumArray[indexPath.row];
            parkingCell.numLabel.text = model.ParkingCode;
        }
        
    }
    
    //判断是车位编号查询还是车牌号查询
    if(self.queryType == 0){
        
        parkingCell.queryType =CarNumQuery;
        
        // 设置item尺寸
        self.layout.itemSize = CGSizeMake(60, 100);
        // 设置item之间的间隔
        self.layout.minimumInteritemSpacing = 20;
        // 设置行之间间隔
        self.layout.minimumLineSpacing = 20;
        // 设置组的内边距
        self.layout.sectionInset = UIEdgeInsetsMake(30, 30, 30, 30);
        
    }else if (self.queryType == 1){
        
        parkingCell.queryType = ParkingNumQuery;
        // 设置item尺寸
        self.layout.itemSize = CGSizeMake(50, 100);
        // 设置item之间的间隔
        self.layout.minimumInteritemSpacing = 30;
        // 设置行之间间隔
        self.layout.minimumLineSpacing = 15;
        // 设置组的内边距
        self.layout.sectionInset = UIEdgeInsetsMake(10, 30, 30, 30);
    }
    return parkingCell;
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    [collectionView deselectItemAtIndexPath:indexPath animated:YES];
    ParkingQueryCell * parkingCell = [collectionView dequeueReusableCellWithReuseIdentifier:cellID forIndexPath:indexPath];
    
    if (self.queryType == 0)
    {
        parkingCell.queryType = CarNumQuery;
        CarNumController * carNumVC = [[CarNumController alloc]init];
        carNumVC.model = self.carNumArray[indexPath.row];
        
        [self.navigationController pushViewController:carNumVC animated:YES];
        
    }else if (self.queryType == 1)
    {
        
        parkingCell.queryType = ParkingNumQuery;
        ParkingNumController * parkingNumVC = [[ParkingNumController alloc]init];
        parkingNumVC.model = self.parkingNumArray[indexPath.row];
        
        [self.navigationController pushViewController:parkingNumVC animated:YES];
    }
    
}
//组头
//这个方法是返回 Header的大小 size
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section
{
    return CGSizeMake(BHscreenW, 10);
}
//这个也是最重要的方法 获取Header的 方法。
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
        UICollectionReusableView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:headerViewID forIndexPath:indexPath];
        UIView * header = [[UIView alloc]initWithFrame:CGRectMake(0, 0, BHscreenW, 10)];
        [headerView addSubview:header];
        header.backgroundColor = BHColor(238, 238, 238);
        
        return headerView;
    }
    return nil;
}
- (BOOL)searchBar:(UISearchBar *)searchBar shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
    
    DLog(@"--------%zd--------%zd",range.length,range.location);
    if (range.location == 0) {
        if (self.queryType == 0) {
            
            [self.carNumArray removeAllObjects];
            [self.collectionView reloadData];
            
        }else if (self.queryType == 1){
            
            
            
            [self.parkingNumArray removeAllObjects];
            [self.collectionView reloadData];
        
        }
        
        self.placehoderImg.hidden = NO;
        self.placehoderImg.hidden = NO;
        
    }

    return YES;
}
-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    if (searchText.length == 0) {
        self.searchText = @"";
        self.isSearch = NO;
        
        [self.parkingNumArray removeAllObjects];
        [self.carNumArray removeAllObjects];

//        DLog(@"车位号个数 --- %ld",self.parkingNumArray.count);
//         DLog(@"车牌号个数 --- %ld",self.carNumArray.count);
//        DLog(@"搜索的结果 === %ld",self.resultArr.count);
        
        [self.collectionView reloadData];
        
        self.placehoderImg.hidden = NO;
        self.titleLabel.hidden = NO;
    }
    NSLog(@" --- %@",searchText);
    self.searchStr = searchText;
    
    [self.resultArr removeAllObjects];
    
    [self.parkingNumArray removeAllObjects];
    [self.carNumArray removeAllObjects];
    
    [self.resultArr removeAllObjects];
    [self.collectionView reloadData];
    
    if (self.queryType == 0) {
        
        for (CarNumQueryModel * model in self.carNumArray) {
            if ([model.CarNo rangeOfString:searchText].location != NSNotFound) {
                [self.resultArr addObject:model.CarNo];
            }
        }
        
    }else if (self.queryType == 1){
        
        for (ParkingQueryModel * model in self.parkingNumArray) {
            if ([model.ParkingCode rangeOfString:searchText].location != NSNotFound) {
                [self.resultArr addObject:model.ParkingCode];
            }
        }
        
    }
    
    if (self.resultArr.count) {
        self.isSearch = YES;
        self.placehoderImg.hidden = YES;
        self.titleLabel.hidden = YES;
        [self.collectionView reloadData];
    }
    
    
}

-(BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar
{

    [self.menu hiddenBackground];
    
    [self.menu hiddenSelectedView:self.tableView];
    
    return YES;
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{

    if (self.queryType == 0) {
        //车牌号数据
        [self postCarNumData];
    }else if (self.queryType == 1){
        
        //车位号数据
        [self postParkingData];
    }
   
    [self.menu hiddenBackground];
    
    [self.menu hiddenSelectedView:self.tableView];
    
    [self.view endEditing:YES];

}
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
    self.isSearch = NO;
    
}

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
    [self.collectionView endEditing:YES];
    self.isSearch = NO;
    
}

#pragma mark - 暂未图
- (void)createPlaceHolder
{
    
    self.placehoderImg = [[UIImageView alloc]init];
    [self.collectionView addSubview:self.placehoderImg];
    self.placehoderImg.image = [UIImage imageNamed:@"ico_query_no"];
    
    [self.placehoderImg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.collectionView).with.offset(0);
        make.top.equalTo(self.collectionView.mas_bottom).with.offset(100);
        make.size.mas_equalTo(CGSizeMake(80, 80));
    }];
    
    self.titleLabel = [[UILabel alloc]init];
    [self.collectionView addSubview:self.titleLabel];
    self.titleLabel.text = @"暂无查询内容";
    
    self.titleLabel.textColor= BHColor(153, 153, 153);
    self.titleLabel.font = BHFont(15);
    self.titleLabel.textAlignment = NSTextAlignmentCenter;
    
    [self.titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.collectionView).with.offset(0);
        make.top.equalTo(self.placehoderImg.mas_bottom).with.offset(10);
        make.size.mas_equalTo(CGSizeMake(100, 25));
    }];
    
}

#pragma mark - 获取车位查询数据
- (void)postParkingData
{
    
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.label.text = @"努力加载数据中...";
    // 隐藏时从父控件中移除
    hud.removeFromSuperViewOnHide = YES;
    hud.backgroundView.style = MBProgressHUDBackgroundStyleSolidColor;
    hud.userInteractionEnabled = YES;
    
    NSDictionary * parms = nil;
    parms = @{
              @"CommunityID":userModel.CommunityID,
              @"ParkingCode":self.searchStr,
              @"uid":userModel.WorkerID,
              @"json":@"\{\"jsonEntity\":\{},\"action\":\"getparkinfo\",\"version\":\"V1.0\"}"
              };

    [HomeNetWorkRequest postParkingQuerySuccess:^(id data) {
        
         [MBProgressHUD hideHUDForView:self.view];
        
        [self.parkingNumArray removeAllObjects];
        
        NSDictionary * dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        
        NSString * str = [NSString stringWithFormat:@"%@",dict[@"Data"]];
        NSData * data2 = [str dataUsingEncoding:NSUTF8StringEncoding];
        NSArray * array = [NSJSONSerialization JSONObjectWithData:data2 options:NSJSONReadingMutableContainers error:nil];
        DLog(@"车位信息的数据 == %@",array);
        
        for (NSDictionary * dict in array) {
            ParkingQueryModel * model = [[ParkingQueryModel alloc]init];
            [model setValuesForKeysWithDictionary:dict];
            [self.parkingNumArray addObject:model];
            DLog(@"车位号 == %@",model.ParkingCode);
        }
        if (self.parkingNumArray.count != 0) {
            self.placehoderImg.hidden = YES;
            self.titleLabel.hidden = YES;
        }else if (self.resultArr.count != 0){
        
            self.placehoderImg.hidden = YES;
            self.titleLabel.hidden = YES;
        
        }else{
            self.placehoderImg.hidden = NO;
            self.titleLabel.hidden = NO;
        }

        [self.collectionView reloadData];
        
    } Fail:^(NSString *errorDes) {
        
      [MBProgressHUD hideHUD];
    } param:parms];
    
}
#pragma mark - 获取车牌号查询数据
- (void)postCarNumData
{
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.label.text = @"努力加载数据中...";
    // 隐藏时从父控件中移除
    hud.removeFromSuperViewOnHide = YES;
    hud.backgroundView.style = MBProgressHUDBackgroundStyleSolidColor;
    hud.userInteractionEnabled = YES;
    
    NSDictionary * parms = nil;
    parms = @{
              @"CommunityID":userModel.CommunityID,
              @"CarNO":self.searchStr,
              @"uid":userModel.WorkerID,
              @"json":@"\{\"jsonEntity\":\{},\"action\":\"getcarinfo\",\"version\":\"V1.0\"}"
              };

    DLog(@"车牌号查询提交参数 == %@",parms);
    [HomeNetWorkRequest postCarNumQuerySuccess:^(id data) {
        
         [MBProgressHUD hideHUDForView:self.view];
        
         [self.carNumArray removeAllObjects];
        
        NSDictionary * dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        
        NSString * str = [NSString stringWithFormat:@"%@",dict[@"Data"]];
        NSData * data2 = [str dataUsingEncoding:NSUTF8StringEncoding];
        NSArray * array = [NSJSONSerialization JSONObjectWithData:data2 options:NSJSONReadingMutableContainers error:nil];
        DLog(@"车牌号信息的数据 == %@",array);
        
        for (NSDictionary * dict in array) {
            CarNumQueryModel * model = [[CarNumQueryModel alloc]init];
            [model setValuesForKeysWithDictionary:dict];
            [self.carNumArray addObject:model];
            DLog(@"车牌号 == %@",model.CarNo);
        }
        if (self.carNumArray.count != 0) {
            self.placehoderImg.hidden = YES;
            self.titleLabel.hidden = YES;
        }
   
        [self.collectionView reloadData];
        
    } Fail:^(NSString *errorDes) {
         [MBProgressHUD hideHUD];
    } param:parms];
    
}

@end
